package com.luyang.framework.web.handler;

import com.luyang.framework.protocol.Result;
import com.luyang.framework.protocol.ResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.Servlet;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;

/**
 * 全局异常处理
 *
 * @author lu_yang
 */
@RestControllerAdvice
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass({Servlet.class, DispatcherServlet.class})
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
public class GlobalExceptionTranslator {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionTranslator.class);

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public Result<Serializable> handleError(MissingServletRequestParameterException e, HttpServletRequest request) {
        logger.error("缺少请求参数, uri:{}", request.getRequestURI(), e);
        String message = String.format("缺少必要的请求参数: %s", e.getParameterName());
        return Result.failure(ResultCode.PARAM_MISS, message);
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentTypeMismatchException.class)
    public Result<Serializable> handleError(MethodArgumentTypeMismatchException e, HttpServletRequest request) {
        logger.error("请求参数格式错误, uri:{}", request.getRequestURI(), e);
        String message = String.format("请求参数格式错误: %s", e.getName());
        return Result.failure(ResultCode.PARAM_TYPE_ERROR, message);
    }

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<Serializable> handleError(MethodArgumentNotValidException e, HttpServletRequest request) {
        logger.error("参数验证失败, uri:{}", request.getRequestURI(), e);
        return handleError(e.getBindingResult());
    }

    private Result<Serializable> handleError(BindingResult result) {
        FieldError error = result.getFieldError();
        assert error != null;
        String message = String.format("%s:%s", error.getField(), error.getDefaultMessage());
        return Result.failure(ResultCode.PARAM_BIND_ERROR, message);
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public Result<Serializable> handleError(NoHandlerFoundException e, HttpServletRequest request) {
        logger.error("404没找到请求, uri:{}", request.getRequestURI(), e);
        return Result.failure(ResultCode.NOT_FOUND, e.getMessage());
    }

    @ExceptionHandler(HttpMessageNotReadableException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<Serializable> handleError(HttpMessageNotReadableException e, HttpServletRequest request) {
        logger.error("消息不能读取, uri:{}", request.getRequestURI(), e);
        return Result.failure(ResultCode.MSG_NOT_READABLE, e.getMessage());
    }

    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    @ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
    public Result<Serializable> handleError(HttpRequestMethodNotSupportedException e, HttpServletRequest request) {
        logger.error("不支持当前请求方法, uri:{}", request.getRequestURI(), e);
        return Result.failure(ResultCode.METHOD_NOT_SUPPORTED, e.getMessage());
    }

    @ExceptionHandler(HttpMediaTypeNotSupportedException.class)
    @ResponseStatus(HttpStatus.UNSUPPORTED_MEDIA_TYPE)
    public Result<Serializable> handleError(HttpMediaTypeNotSupportedException e, HttpServletRequest request) {
        logger.error("不支持当前媒体类型, uri:{}", request.getRequestURI(), e);
        return Result.failure(ResultCode.MEDIA_TYPE_NOT_SUPPORTED, e.getMessage());
    }
}
